<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Response;

class ForceCheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $uuid = $request->header('X-Request-ID');
        $token = $request->bearerToken();
        if($uuid && $token){
            $user = User::where('token_uuid', $uuid)->first();
            if($user && Hash::check($token, $user->token)){
                if(!$user->token_created_at->addSeconds(Env::get('TOKEN_LIFETIME')+0)->isPast()){
                    $request->merge(['user' => $user]);
                    //Auth::login($user);
                    return $next($request);
                }
            }
        }
        return response()->json([
            "msg" => "Unauthorized",
        ],401);
    }

}
